import type {
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
} from '@fast-crud/fast-crud';

import type { FormRulesExt } from '#/api';
import type { DefDictModel } from '#/api/devOperation/system/model/defDictModel';

import { ref } from 'vue';

import { useAccess } from '@vben/access';

import { RuleType } from '#/api';
import { BaseDictApi } from '#/api/basic/base/baseDict';
import { PermCode } from '#/enums/perm';
import { useMessage } from '#/hooks/web/useMessage';
import { $t } from '#/locales';
import {
  deleteButton,
  indexColumn,
  STATE_CONSTANT_DICT,
  transformQuery,
  transformRes,
} from '#/plugins/fast-crud/common';

const { hasPermission } = useAccess();
const permCode = PermCode.basic.base.dict;

export function createCrudOptions(
  props: CreateCrudOptionsProps<DefDictModel.DefDictResultVO, any>,
): CreateCrudOptionsRet<DefDictModel.DefDictResultVO> {
  const selectedRowKeys = ref<string[]>([]);
  const currentRow = ref();
  const { itemTableRef } = props.context;
  const { createMessage } = useMessage();
  const onCurrentRowChange = (id: string) => {
    currentRow.value = id;
    itemTableRef.value.setData({ parentId: id });
    itemTableRef.value.doRefresh();
  };

  return {
    crudOptions: {
      id: 'base_dict',
      form: {
        wrapper: {
          is: 'a-drawer',
          draggable: false,
          size: '50%',
        },
      },
      request: {
        pageRequest: BaseDictApi.pageRequest,
        addRequest: BaseDictApi.addRequest,
        editRequest: BaseDictApi.editRequest,
        delRequest: BaseDictApi.delRequest,
        infoRequest: BaseDictApi.infoRequest,
        transformQuery: (query) => {
          const tq = transformQuery(query);
          tq.sort = 'createdTime';
          tq.order = 'desc';
          return tq;
        },
        transformRes: (prop) => {
          const { res } = prop;
          if (res.records && res.records.length > 0) {
            currentRow.value = res.records[0].id;
            itemTableRef.value.setData({ parentId: res.records[0].id });
            itemTableRef.value.doRefresh();
          } else {
            itemTableRef.value.setData({ parentId: undefined });
            itemTableRef.value.setTableData([]);
          }
          return transformRes(prop);
        },
      },
      actionbar: {
        buttons: {
          add: { show: false },
          ...deleteButton({
            crudExpose: props.crudExpose,
            selectedRowKeys,
            removeFn: BaseDictApi.removeFn,
            role: permCode.delete,
            callback: async (flag) => {
              if (flag) {
                createMessage.info('删除成功');
                selectedRowKeys.value = [];
                await props.crudExpose?.doRefresh();
                itemTableRef.value.setData({ parentId: undefined });
                itemTableRef.value.setTableData([]);
              }
            },
          }),
          import: {
            show: hasPermission(permCode.import),
            text: $t('common.title.import'),
            click() {
              props.context.defDictModalRef.value?.open();
            },
          },
        },
      },
      table: {
        striped: true,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          selectedRowKeys,
          onChange: (changed: string[]) => {
            selectedRowKeys.value = changed;
          },
        },
        customRow(record: any, _index: number) {
          const clazz = record.id === currentRow.value ? 'fs-current-row' : '';
          return {
            style: 'cursor: pointer;',
            onClick() {
              onCurrentRowChange(record.id);
            },
            class: clazz,
          };
        },
      },
      rowHandle: {
        width: 80,
        buttons: {
          edit: { show: hasPermission(permCode.edit) },
          view: { show: false },
          remove: { show: false },
          copy: { show: false },
        },
      },
      columns: {
        ...indexColumn(props.crudExpose),
        key: {
          title: $t('devOperation.system.defDict.key'),
          type: 'text',
          search: { show: true },
          editForm: {
            component: { disabled: true },
          },
          column: { show: false },
        },
        name: {
          title: $t('devOperation.system.defDict.name'),
          type: 'text',
          search: { show: true },
        },
        state: {
          title: $t('devOperation.system.defDict.state'),
          type: 'dict-radio',
          dict: STATE_CONSTANT_DICT,
          search: { show: true, component: { mode: 'multiple' } },
          addForm: { value: true },
          column: { width: 60 },
        },
        sortValue: {
          title: $t('devOperation.system.defDict.sortValue'),
          type: 'number',
          column: {
            show: false,
          },
        },
        remark: {
          title: $t('devOperation.system.defDict.remark'),
          type: 'textarea',
          column: { show: false },
        },
      },
    },
  };
}

export const frontRules = {
  editForm: {
    rules: (): FormRulesExt => {
      return {
        key: {
          type: RuleType.and,
          rules: [
            {
              trigger: 'blur',
              type: 'string',
              message: '标识重复',
              asyncValidator: async (_: any) => {},
            },
          ],
        },
      };
    },
  },
};
